import $axios from 'axios'
import config from './config'
var util = {
  /**
   * 格式化时间
   */
  formatTime: date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  },

  formatNumber: n => {
    n = n.toString()
    return n[1] ? n : '0' + n
  },
  /**
   * 清除详情富文本自带样式
   */
  formatHtml: content => {
    content = content.replace(/\<img/gi, '<img style="width:100% !important;height:auto !important;margin:0;display:flex;" ');
    content = content.replace(/style="/gi, 'style="max-width:100% !important;table-layout:fixed;word-wrap:break-word;word-break;break-word;');
    // content = content.replace(/\<table/gi, '<table style="table-layout:fixed;word-wrap:break-word;word-break;break-all;" ');
    // content = content.replace(/\<td/gi, '<td  cellspacing="0" cellpadding="0" border="0" style="display:block;vertical-align:top;margin: 0px; padding: 0px; border: 0px;outline-width:0px;" ');
    content = content.replace(/width=/gi, 'sss=');
    content = content.replace(/height=/gi, 'sss=');
    content = content.replace(/ \/\>/gi, ' style="max-width:100% !important;height:auto !important;margin:0;display:block;" \/\>');
    return content;
  },
  /**
   * 根据相隔时间戳，计算相隔时间
   */
  betweenTime: (betweenTimestamp) => {
    // 正的时间还是负的时间
    let signs = 1
    if (betweenTimestamp < 0) {
      betweenTimestamp = -betweenTimestamp
      signs = 0
    }

    if (betweenTimestamp > 1000) {
      let time = betweenTimestamp / 1000;
      // 获取天、时、分、秒
      let day = parseInt(time / (60 * 60 * 24));
      let hou = parseInt(time % (60 * 60 * 24) / 3600);
      let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
      let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
      return {
        day: `${util.timeFormat(day)}`,
        hou: `${util.timeFormat(hou)}`,
        min: `${util.timeFormat(min)}`,
        sec: `${util.timeFormat(sec)}`,
        signs: signs
      }
    }
    return {
      day: '00',
      hou: '00',
      min: '00',
      sec: '00',
      signs: signs
    }
  },
  /**
   * 计算相隔时间戳
   */
  betweenTimestamp (startTime, endTime) {
    let newTime = new Date().getTime()
    let betweenTime = 0;
    // 还没开始 相差时间为负数
    if (newTime < startTime) {
      betweenTime = newTime - startTime
    }
    // 还没结束
    else {
      betweenTime = endTime - newTime
    }
    return betweenTime;
  },
  /**
   * 小于10的格式化函数
   */
  timeFormat: (times) => {
    return times < 10 ? '0' + times : times;
  },

  /**
   * 日期转时间戳
   */
  dateToTimestamp: (dateStr) => {
    if (!dateStr) {
      return ''
    }
    let newDataStr = dateStr.replace(/\.|\-/g, '/')
    let date = new Date(newDataStr);
    let timestamp = date.getTime();
    return timestamp
  },

  /**
   * 改变日期
   */
    tsToDate(number, format) {
    var formateArr = ["Y", "M", "D", "h", "m", "s"];
    var returnArr = [];

    var date = new Date(number);
    returnArr.push(date.getFullYear());
    returnArr.push(
      date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1
    );
    returnArr.push(
      date.getDate() < 10 ? "0" + date.getDate() : date.getDate()
    );

    returnArr.push(
      date.getHours() < 10 ? "0" + date.getHours() : date.getHours()
    );
    returnArr.push(
      date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()
    );
    returnArr.push(
      date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds()
    );

    for (var i in returnArr) {
      format = format.replace(formateArr[i], returnArr[i]);
    }
    return format;
  },
  /**
   * 价格处理
   */
  parsePrice: (value) => {
    var val = Number(value)
    if (!val) {
      val = 0;
    }
    // 截取小数点后两位，并以小数点为切割点将val转化为数组
    return val.toFixed(2).split(".");
  },

  /**
   * 手机号正则校验
   */
  checkPhoneNumber: (phoneNumber) => {
    var regexp = /^[1][0-9]{10}$/
    return regexp.test(phoneNumber)
  },

  /**
   * 用户名正则校验
   */
  checkUserName: (userName) => {
    var regexp = /^([a-zA-Z0-9_]{4,16})$/
    return regexp.test(userName)
  },

  /**
   * 处理参数
   * @param {obj}  to: 目标页面路由信息
   */
  getPageInfo: (to) => {
    var pathName = to.name
    var params = to.params
    var pageInfo = {}
    if (pathName === 'index') {
      pageInfo.pageId = 1
    } else if (pathName === 'detail-prodId') {
      pageInfo.pageId = params.bannerEnter === '1' ? 2 : params.groupActivityId ? 5: 3
      pageInfo.bizType = params.groupActivityId ? 1 : 0
      pageInfo.bizData = params.prodId
    } else if (pathName === 'secdetail-seckillId') {
      pageInfo.pageId = 4
      pageInfo.bizType = 2
      pageInfo.bizData = params.seckillId
    } else if (pathName === 'list') {
      pageInfo.pageId = 6
    } else if (pathName === 'special-discount') {
      pageInfo.pageId = 7
    } else if (pathName === 'cart') {
      pageInfo.pageId = 8
    } else if (pathName === 'order-detail') {
      pageInfo.pageId = 9
    } else if (pathName === 'payment') {
      pageInfo.pageId = 10
      pageInfo.bizData = sessionStorage.getItem('pay_orderNumber')
    }
    // else if (pathName === 'uc-order' && query.total_amount) {
    //   pageInfo.pageId = 11
    //   pageInfo.bizData = sessionStorage.getItem('pay_orderNumber')
    // }
    else if (pathName === 'user-center') {
      pageInfo.pageId = 12
    } else if (pathName === 'user-center-uc-order') {
      pageInfo.pageId = 13
    }
    return pageInfo
  },

  /**
   * 获取唯一值
   */
  getUuid: () => {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
  },

  saveLog(flowData, visitType) {
    var flowAnalysisLogDto = Object.assign(flowData)
    flowAnalysisLogDto.visitType = visitType
    $axios.post(config.path + '/flowAnalysisLog', flowAnalysisLogDto).then(({ data }) => {

    })
  },

  /**
   * 记录页面点击次数
   */
  tapLog(visitType, orderNumbers, isPayRes, prodNum) {
    // 更新会话时间
    localStorage.setItem('sessionTimeStamp', new Date().getTime())
    var flowAnalysisLogDto = JSON.parse(localStorage.getItem('flowAnalysisLogDto'))

	flowAnalysisLogDto.visitType = visitType || 3
	flowAnalysisLogDto.nums = prodNum || undefined
    // 支付页面单独处理
    if (orderNumbers) {
      visitType = 1
      flowAnalysisLogDto.orderNumbers = orderNumbers
      flowAnalysisLogDto.step = flowAnalysisLogDto.step + 1
      flowAnalysisLogDto.pageId = !isPayRes ? 10 : 11
    }
    this.saveLog(flowAnalysisLogDto, visitType)
  }
}


export default util

/**
 * 防抖
 */
export function _debounce (fn, delay) {
  var delay = delay || 200;
  var timer;
  return function () {
    var th = this;
    var args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(function () {
      timer = null;
      fn.apply(th, args);
    }, delay);
  };
}

import Cookies from 'js-cookie'

const LangKey = 'hb_lang' // 语言

export function getLanguage() {
  return Cookies.get(LangKey)
}

export function setLanguage(data) {
  return Cookies.set(LangKey, data)
}

export function removeLanguage() {
  return Cookies.remove(LangKey)
}


/**
 * 函数节流
 * @param fn
 * @param interval
 * @returns {Function}
 * @constructor
 */
export function _throttle (fn, t) {
  let last;
  let timer;
  let interval = t || 500;
  return function () {
    let args = arguments;
    let now = +new Date();
    if (last && now - last < interval) {
      clearTimeout(timer);
      timer = setTimeout(() => {
        last = now;
        fn.apply(this, args);
      }, interval);
    } else {
      last = now;
      fn.apply(this, args);
    }
  }
};

export function addUrlParam(uri, key, value) {
	if(!value) {
		return uri;
	}
	var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
	var separator = uri.indexOf('?') !== -1 ? "&" : "?";
	if (uri.match(re)) {
		return uri.replace(re, '$1' + key + "=" + value + '$2');
	}
	else {
		return uri + separator + key + "=" + value;
	}
}
